//
//  RegistUserViewController.m
//  PatientApp
//
//  Created by chirui on 2017/5/17.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "RegistUserViewController.h"
#import "RegistMessageViewController.h"



@interface RegistUserViewController ()
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIView *surePasswordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UITextField *surePasswordYext;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;


@property (nonatomic,copy) NSString * typeStr;

@end

@implementation RegistUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    _typeStr = @"0";
    
    self.okBtn.selected = NO;
    self.sureBtn.layer.cornerRadius = 20.f;
    self.sureBtn.layer.masksToBounds = YES;
        
    self.codeBtn.layer.cornerRadius = 5.f;
    self.codeBtn.layer.masksToBounds = YES;
    self.codeBtn.layer.borderWidth = 0.5;
    self.codeBtn.layer.borderColor = NavBackColor.CGColor;
    
    //    self.codeBtn.layer.cornerRadius = 22.f;
    //    self.codeBtn.layer.masksToBounds = YES;
    
}

- (IBAction)backClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

- (IBAction)codeBtnClick:(UIButton *)sender {
    
    if (self.phoneText.text.length!=11) {
        
        SHuiMBhudTextTimeStr(@"请输入正确的手机号");
        return;
    }
       [self sendMSNetWorkingFor];
  
}
- (IBAction)okBtnClick:(UIButton *)sender {
    
    self.okBtn.selected = !self.okBtn.selected;
    
    if (self.okBtn.selected) {
        
        _typeStr = @"1";
    }else {
    
        _typeStr = @"0";
    }
    
}
- (IBAction)userMessage:(UIButton *)sender {
    
    RegistMessageViewController * message =[[RegistMessageViewController alloc]init];
    
   [self presentViewController:message animated:YES completion:^{
       
   }];
    
}
- (IBAction)sureBtnClick:(UIButton *)sender {
    
    
   if (self.phoneText.text.length!=11) {
        
        [SHJudgeTools MBProgressHUDPromptWith:@"手机号码不正确" On:self.view];
        return;
        
    }else if(_codeText.text.length<1){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"验证码不能为空" On:self.view];
        return;
        
    }else if(_passwordText.text.length<6){
        [SHJudgeTools MBProgressHUDPromptWith:@"密码不能少于6位" On:self.view];
        return;
    }else if (![_passwordText.text isEqualToString:_surePasswordYext.text]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"两次密码不一致" On:self.view];
        return;
        
    }else if ([_typeStr isEqualToString:@"0"]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"请勾选同意用户协议" On:self.view];
        return;
        
    } else{
        
        [self registerNetWorking];
    }

}

#pragma mark  网络请求


-(void)registerNetWorking {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,register_user_api];


    NSDictionary * dic = @{@"username":_phoneText.text,
                           @"password":_passwordText.text,
                           @"code":_codeText.text
                           };

     [MBProgressHUD showMessag:@"正在注册..." withDelay:0 toView:self.view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] intValue]==200) {

            [MBProgressHUD showMessag:@"注册成功" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{

                    [self dismissViewControllerAnimated:YES completion:^{
                        //
                    }];

                });
            });

        } else {

            [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        }
    
    } failed:^(NSError *error) {
        NSLog(@"ERROR ==%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        SHuiMBhudTextNetError;
    }];
    
}

// 验证码
-(void)sendMSNetWorkingFor{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,forget_SendSms_api];
    NSDictionary * parameter = @{@"username":_phoneText.text,
                                 @"type":@"register"
                                 };
    NSLog(@"param ==%@",parameter);

    SHuiMBhubNoTimeStr(@"正在发送");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"发送成功");

            __block int timeout = 60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=1){
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{

                        [self.codeBtn setTitle:@"获取" forState:UIControlStateNormal];
                        self.codeBtn.userInteractionEnabled = YES;
                    });
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{

                        NSString  * time = [NSString stringWithFormat:@"%d(秒)",timeout];
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        [self.codeBtn setTitle:time forState:UIControlStateNormal];
                        [UIView commitAnimations];
                        self.codeBtn.userInteractionEnabled = NO;
                        
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);

        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
